// pages/usercenter/pladge/pladge.js
import {
  users
} from '../../../tools/users'
import {
  ui
} from '../../../tools/ui'
import {
  pay
} from '../../../tools/pay'
import {
  checkTool
} from '../../../tools/check'
import {
  msg
} from '../../../tools/msg'
import {
  ds
} from '../../../tools/data'
import {
  dsx
} from '../../../tools/datax'
import {
  dateTool
} from '../../../tools/date';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    values: {},
    user: null,
    action: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // wx.cloud.callFunction({
    //   name: 'updateBarrelInfo'
    // }).then(res => {
    //   console.log(res)
    // })

    const {
      action,
      staffId
    } = options
    this.setData({
      action,
      staffId
    })
    this.action = action
    this.init()
  },
  init() {
    const action = this.action
    if (action == 'manage') {
      const {
        staffId
      } = this.data
      this.loadStaffInfo(staffId)
      return
    }
    this.loadMyInfo()
  },
  loadMyInfo() {
    ui.loading()
    dsx.cloudGetByOpenid('users')
      .then(res => {
        const user = res.result.data[0] || {}
        this.setShowInfo(user)
        ui.loading(false)
      })
  },
  loadStaffInfo(staffId) {
    ui.loading()
    ds.coll('users')
      .where({
        _id: staffId
      })
      .get()
      .then(res => {
        const user = res.data[0]
        this.setShowInfo(user)
        ui.loading(false)
      })
  },
  setShowInfo(user) {
    const barrelPay = user.barrelPay || {}
    const payList = barrelPay.list || []
    let pladge = 0,
      hasRefound = false
    for (const record of payList) {
      if (['success', 'refound', 'refound_refuse'].indexOf(record.payStatus) >= 0) pladge += record.pladge
      record.statusDesc = this.descStatusPay(record.payStatus)
      if (record.statusDesc == '退款中') hasRefound = true
    }

    const desc = {
      barrel: barrelPay.barrel || '无记录',
      pladge: '￥' + pladge
    }
    this.setData({
      payList: []
    })
    this.setData({
      values: {
        barrel: barrelPay.barrel || 0
      },
      user,
      desc,
      payList,
      hasRefound
    })
  },
  descStatusPay(payStatus) {
    return ({
      'wait': '未支付',
      'success': '已支付',
      'refound': '退款中',
      'refound_success': '已退款',
      'refound_refuse': '已拒绝退款'
    })[payStatus] || '无记录'
  },
  async onDeleteTap(e) {
    if (!await ui.confirmx('确定删除吗')) return
    ui.loading()
    const outTradeNo = ui.eventData(e, 'outtradeno')
    const _ = dsx.cmd
    dsx.coll('users')
      .where({
        _id: this.data.user._id
      })
      .update({
        data: {
          barrelPay: {
            list: _.pull({
              outTradeNo: _.eq(outTradeNo)
            })
          }
        }
      }).then(res => {
        ui.loading(false)
        ui.toast(res.errMsg.endsWith(':ok'), null, () => {
          this.init()
        })
      })
  },
  async onAgreeRefoundTap(e) {
    if (!await ui.confirmx('确定同意退款吗')) return

    const item = ui.eventData(e, 'item'),
      index = ui.eventData(e, 'index')
    this.doRefound(item, index)
      .then(res => {
        this.init()
      })
  },
  async refoundAllTap() {
    if (!await ui.confirmx('确定同意全部退款吗')) return
    const {
      payList
    } = this.data
    let success = 0
    const records = payList.filter(ele =>
      ele.payStatus == 'refound'
    )
    payList.forEach(async (record, index) => {
      if (record.payStatus == 'refound') {
        const res = await this.doRefound(record, index)
        success += (res.errMsg.endsWith(":ok") ? 1 : 0)
        ui.toast(success > 0, `已处理${success}/${records.length}个`, res => {
          if (index == payList.length - 1) this.init()
        })
      }
    })
  },
  doRefound(item, index) {
    return new Promise((resolve, reject) => {
      pay.refound({
        totalFee: item.pladge,
        refoundFee: item.pladge,
        outTradeNo: item.outTradeNo,
        title: '空桶押金-退款'
      }, (success, res) => {
        if (!success) {
          reject(res)
          return
        }
        this.updatePladge(item, index).then(res => {
          resolve(res)
        })
      })
    })
  },
  async onRefuseRefoundTap(e) {
    if (!await ui.confirmx('确定拒绝退款吗')) return

    const item = ui.eventData(e, 'item'),
      index = ui.eventData(e, 'index')
    ui.loading()
    const _ = ds.cmd
    dsx.cloudUpdate('users', this.data.user._id, {
      [`barrelPay.list.${index}.payStatus`]: 'refound_refuse'
    }).then(res => {
      ui.loading(false)
      ui.toast(res.errMsg.endsWith(':ok'), null, res => {
        this.init()
      })
    })
  },
  async onApplyRefoundTap(e) {
    if (!await ui.confirmx('确定申请退款吗')) return

    const item = ui.eventData(e, 'item'),
      index = ui.eventData(e, 'index')
    this.applyRefound(item, index)
  },
  refoundListTap() {
    wx.navigateTo({
      url: '/pages/usercenter/pladge/list/pladgeList',
    })
  },
  applyRefound(item, index) { // 申请退款
    const {
      user
    } = this.data
    ui.loading()
    const _ = ds.cmd
    ds.coll('users').where({
        _id: user._id
      })
      .update({
        data: {
          [`barrelPay.list.${index}`]: {
            payStatus: 'refound',
            updateTime: new Date().getTime()
          }
        }
      })
      .then(res => {
        this.init()
        this.notifyAdmin(user, item.pladge)
        ui.loading(false)
      })
  },
  async updatePladge(item, index) { // refound_success
    const _ = dsx.cmd
    const key_payStatus = `barrelPay.list.${index}.payStatus`
    const key_refound = `barrelPay.list.${index}.refound`
    return dsx.cloudUpdate('users', this.data.user._id, {
      [key_payStatus]: 'refound_success',
      [key_refound]: 0
    })
  },
  onValueChange(e) {
    const {
      values
    } = this.data
    const name = e.currentTarget.dataset.name
    const value = e.detail.value
    values[name] = value
    this.setData({
      values
    })
  },
  onSave() {
    const {
      values,
      user
    } = this.data
    checkTool.check([{
      value: values.barrel,
      regex: checkTool.CommonRegex.integer,
      title: '空桶个数'
    }])
    ui.loading()
    dsx.cloudUpdate('users', user._id, {
        barrelPay: {
          barrel: +values.barrel
        }
      })
      .then(res => {
        ui.loading(false)
        ui.toast(res.result.errMsg.endsWith(':ok'))
      })
  },
  gotoUserInfo() {
    const {
      user
    } = this.data
    wx.navigateTo({
      url: '/pages/usercenter/staff/edit/index?action=edit&id=' + user._id,
    })
  },
  async notifyAdmin(user, refoundFee) {
    const adminRes = await ds.coll('users')
      .where({
        role: 'admin'
      })
      .get()

    const addrMobile = await this.getAddrMobile(user)
    const admins = adminRes.data
    admins.forEach(async ele => {
      const datetime = new Date().getTime()
      try { // 微信服务通知       
        await msg.push({
          touser: ele._openid, // openid of user
          page: '/pages/usercenter/pladge/pladge?action=manage&staffId=' + user._id,
          amount: refoundFee,
          title: '桶押金退款申请',
          remark: addrMobile || user.phoneNumber || '',
          datetime: datetime + ''
        })
      } catch (err) {
        console.error(err)
      }

      try { // 短信
        await wx.cloud.callFunction({
          name: 'sendSmsTc',
          data: {
            templateName: "refound_apply",
            templateParamList: [dateTool.format(datetime, 'M月d日hh点'), "1", '用户' + user.phoneNumber + '的桶押金'],
            phoneNumberList: ["+86" + user.phoneNumber],
            sessionContext: 'pladge refund apply'
          }
        })
      } catch (err) {
        console.error(err)
      }
    })
  },
  async getAddrMobile(user) {
    const res = await ds.coll('delivery_addr')
      .where({
        mobile: ds.cmd.exists(true)
      })
      .get()
    return res.data?.[0]?.mobile
  },
  onPullDownRefresh() {
    this.init(this.data.action)
  }
})